import { useChatStore } from '@/stores/chat'
import { useUserStore } from '../../stores/user'
import { useMenuStore } from '@/stores/menu'

const menuStore = useMenuStore()
const chatStore = useChatStore()
const userStore = useUserStore()
class MessageHandler {


  /**
   * 处理用户消息
   * @param data
   */
  userMessage(data) {
    const {content , sessionId , contactId , messageId , createTime } = data.data


    const insertObj = {
      messageId,
      sessionId,
      contactId,
      content,
      type: 2,
      createTime: createTime,
      createUser: userStore.uid,
      status: 1
    }

    window.ipcRenderer.invoke('save-message' , insertObj)
      .then(res => {
        console.log('收到：', res)

        // 判断收到的消息是不是当前会话
        if (chatStore.currentChat && chatStore.currentSessionId === sessionId) {
          chatStore.messageList.unshift(insertObj)
        }

        chatStore.getSessionList()


      })





  }


  /**
   * 初始化会话
   */
  initSession(res) {
    const data = res.data
    window.ipcRenderer.invoke('start-init-session' , data)
      .then((res) => {
        chatStore.getSessionList()
      })
  }


  /**
   * 初始化会话
   */
  initSessionInfo(res) {
    const data = res.data
    window.ipcRenderer.invoke('start-init-sessionInfo' , data)
      .then((res) => {
        chatStore.getSessionList()
      })
  }



  /**
   * 联系人申请
   * @param data
   */
  contactApply(data) {
    menuStore.noticeNumber.contact++
  }


  /**
   * 收到电话
   */
  receiveCall(data) {
    const dataInfo = data.data
    const obj = {
      targetUserId: dataInfo.targetUserId,
      sessionId: dataInfo.roomId,
      type: dataInfo.type,
    }
    window.ipcRenderer.send('receiveCall' , obj)
  }


  /**
   * 挂断电话
   */
  stopCall(data) {
    const dataInfo = data.data
    const obj = {
      targetUserId: dataInfo.targetUserId,
      sessionId: dataInfo.roomId,
      type: dataInfo.type,
    }
    window.ipcRenderer.send('stopCallByReceiver' , obj)
  }


}





export default new MessageHandler()
